<template>
  <a-card>
    <Header :title="'返回'" :subTitle="subTitle" :hasBackPath="true" @headerBack="$router.back()"></Header>
    <!-- {{ruleList}}description -->
    <!--    sendType发券类型1微信券2礼券3纸质券-->
    <a-spin :spinning="spinning" size="large">
      <a-form-model
        ref="rulesForm"
        :model="form"
        :rules="rules"
        :labelCol="{ lg: { span: 5 }, sm: { span: 7 } }"
        :wrapperCol="{ lg: { span: 14 }, sm: { span: 17 } }"
      >
        <a-form-model-item v-if="departmentId" label="申请部门" prop="flow_id" key="flow_id">
          <template>
            <a-select v-model="form.flow_id" style="width: 50%;">
              <a-select-option :value="item.id" v-for="(item, index) in departments" :key="index">
                {{ item.department }}
              </a-select-option>
            </a-select>
            <div style="margin-left: 5%;;width: 45%;display: inline-block;vertical-align: top;line-height: 30px;">
              申请用途：{{usefor}}
            </div>
          </template>
          <!-- <a-select v-else v-model="form.flow_id" style="width: 50%;">
            <a-select-option :value="item.id" v-for="(item, index) in [{department:'总裁办', id: 0}]" :key="index">
              {{ item.department }}
            </a-select-option>
          </a-select> -->
        </a-form-model-item>
        <a-form-model-item v-else label="申请部门" prop="department" key="department">
          <a-input
            allowClear
            v-model="form.department"
            placeholder="请输入"
          />
        </a-form-model-item>
        <a-form-model-item v-if="sendType==3" label="城市" prop="city">
          <a-input
            allowClear
            v-model="form.city"
            placeholder="请输入"
          />
        </a-form-model-item>
        <a-form-model-item v-if="sendType==3" label="店仓" prop="store">
          <a-input
            allowClear
            v-model="form.store"
            placeholder="请输入"
          />
        </a-form-model-item>
        <!-- <a-form-model-item label="申请用途" prop="applyUse">
          <a-select v-model="form.applyUse">
            <a-select-option :value="item" v-for="(item, index) in applyUseList" :key="index">
              {{ item }}
            </a-select-option>
          </a-select>
        </a-form-model-item> -->
        <a-form-model-item label="备注" prop="remarks">
          <a-textarea v-model="form.remarks" placeholder="请输入" :maxLength="250" :rows="4"/>
        </a-form-model-item>
        <a-form-model-item label="关联优惠券" required>
          <a-button type="primary" icon="plus" @click="handleAddAssociatedCoupon">关联新的优惠券</a-button>
          <a-table
            class="association-list"
            style="margin-top: 15px;"
            size="middle"
            :rowKey="(record,index)=>{return index}"
            :columns="sendType==2 ? relationColumns : [...relationColumns.slice(0,1), ...relationColumns.slice(2)]"
            :data-source="form.chooseVoucherRule"
            :pagination="false"
          >
            <span class="product-wrapper" slot="couponType" slot-scope="text, record, index">
              <a-form-model-item label="" :prop="`chooseVoucherRule.${index}.id`"
                                 :rules="{ required: true, message: '请选择', trigger: 'change' }">
                 <a-select v-model="record.id" style="width: 280px;" show-search :filter-option="filterOption">
<!--                   <div slot="dropdownRender" slot-scope="menu" style="margin-bottom: 4px;">-->
<!--                    <v-nodes :vnodes="menu"/>-->
<!--                    <a-divider style="margin: 4px 0;"/>-->
<!--                     <div style="text-align: center;" @mousedown="e => e.preventDefault()">-->
<!--                       <a-pagination size="small"-->
<!--                                     @change="handleCouponCurrentChange"-->
<!--                                     v-model="couponCurrent"-->
<!--                                     :pageSize="couponPageSize"-->
<!--                                     :total="couponTotal"/>-->
<!--                     </div>-->
<!--                  </div>-->

                  <a-select-option :value="item.id" :title="item.vouName+(item.awardid)" v-for="item in ruleList" @click.native="ruleChange(item, index)"
                                   :key="item.id">
                  {{ item.vouName }}({{item.awardid}})
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </span>
            <span slot="sort" slot-scope="text, record, index">
              <a-icon type="arrow-up" @click="handleUp(index)"
                      style="margin-bottom: 24px;margin-right: 5px;cursor: pointer;"/>
              <a-icon type="arrow-down" @click="handleDown(index)" style="margin-bottom: 24px;cursor: pointer;"/>
            </span>
            <span slot="description" :title="record.description" class="description" slot-scope="text, record, index">
              {{record.description}}
            </span>
            <span class="product-wrapper" slot="couponNum" slot-scope="text, record, index">
              <a-form-model-item label="" :prop="`chooseVoucherRule.${index}.num`"
                                 :rules="{ required: true, message: '请输入', trigger: 'blur' }">
                <a-input-number v-model="record.num" :min="1" style="width: 100%;"/>
              </a-form-model-item>
            </span>
            <span slot="action" slot-scope="text, record, index">
              <a-popconfirm title="请确认是否删除本条信息？" @confirm="handleDeletAssociatedCoupon(index)">
                <a-icon type="delete" style="margin-bottom: 24px;cursor: pointer;"/>
              </a-popconfirm>
            </span>
          </a-table>
        </a-form-model-item>
        <a-form-model-item label="发放公众号" prop="wechatno" v-if="sendType!=3">
          <a-select v-model="form.wechatno" style="width: 50%;">
            <a-select-option :value="item.weid" v-for="item in wechatInfos" :key="item.weid">
              {{ item.name }}
            </a-select-option>
          </a-select>
          <div>注：若发放对象未关注选择的公众号，将发放至其他关注的公众号</div>
        </a-form-model-item>
        <a-form-model-item label="发放对象" v-if="sendType!=3" required>
          <SendUser :id="id" ref="sendUser" :sendType="sendType" @checkCard="checkCard"
                    @checkFollow="checkFollow"></SendUser>
        </a-form-model-item>
        <a-form-model-item label="领券模版" prop="applyTemplateId" v-if="sendType==2">
          <a-select v-model="form.applyTemplateId" style="width: 50%;">
            <a-select-option :value="item.id" v-for="item in showPageVoList" :key="item.id">
              {{ item.templateName }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <template v-if="sendType==1">
          <a-form-model-item label="短信提示" class="hidden-title">
            <div>是否对未关注公众号用户进行短信提示：</div>
            <a-radio-group v-model="form.isFollow">
              <a-radio :value="1">是</a-radio>
              <a-radio :value="2">否</a-radio>
            </a-radio-group>
            <a-form-model-item label="" v-if="form.isFollow == 1" prop="smsTemplateIdBynosub">
              <a-select v-model="form.smsTemplateIdBynosub" style="width: 50%;">
                <a-select-option :value="item.id" v-for="item in smstempList" :key="item.id">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
            <div>是否对未开卡用户进行短信提示：</div>
            <a-radio-group v-model="form.isCard">
              <a-radio :value="1">是</a-radio>
              <a-radio :value="2">否</a-radio>
            </a-radio-group>
            <a-form-model-item label="" v-if="form.isCard == 1" prop="smsTemplateIdBynocard">
              <a-select v-model="form.smsTemplateIdBynocard" style="width: 50%;">
                <a-select-option :value="item.id" v-for="item in smstempList" :key="item.id">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-form-model-item>
        </template>
        <a-divider/>
        <a-form-model-item :wrapperCol="{ span: 24 }" style="text-align: center">
          <a-button htmlType="submit" type="primary" :disabled="submitFlag" @click="handleSubmit">确认提交</a-button>
          <div style="color: red;">一旦提交成功，优惠券将直接发放生效，请认真确认所填信息！</div>
        </a-form-model-item>
      </a-form-model>
    </a-spin>
  </a-card>
</template>
<script>
  import {
    addAndEditCoupon,
    ruleList,
    submit,
    printDetails
  } from '@/api/headquartersCoupon/index'
  import SendUser from './components/SendUser'
  import { mapGetters } from 'vuex'
  import Header from '@/views/box/components/layouts/Header'
  const relationColumns = [
    {
      title: '优惠券',
      width: '260px',
      scopedSlots: { customRender: 'couponType' }
    },
    {
      title: '展示顺序',
      align: 'center',
      width: '90px',
      scopedSlots: { customRender: 'sort' }
    },
    {
      title: '券活动描',
      align: 'center',
      width: '150px',
      scopedSlots: { customRender: 'description' }
    },
    
    {
      title: '张数',
      width: '150px',
      scopedSlots: { customRender: 'couponNum' }
    },
    {
      title: '操作',
      width: '150px',
      align: 'center',
      scopedSlots: { customRender: 'action' }
    }
  ]
  export default {
    components: {
      VNodes: {
        functional: true,
        render: (h, ctx) => ctx.props.vnodes
      },
      SendUser,
      Header
    },
    data() {
      return {
        applyUseList: [],
        couponCurrent: 1,
        couponPageSize: 1000,
        couponTotal: 0,
        submitFlag: false,
        relationColumns,
        spinning: false,
        departments: [],
        wechatInfos: [],
        showPageVoList: [],
        smstempList: [],
        sendType: '', // 发券类型1微信券2礼券3纸质券
        ruleList: [],
        form: {
          isCard: 2,
          isFollow: 2,
          flow_id: '',
          remarks: '',
          wechatno: '',
          applyUse: '',
          applyTemplateId: '',
          smsTemplateIdBynosub: '',
          smsTemplateIdBynocard: '',
          store: '',
          city: '',
          department: '',
          chooseVoucherRule: [
            {
              id: '',
              name: '',
              num: 1,
              amtAcount: '',
              couType: '',
              vouDis: '',
              description: ''
            }
          ]
        },
        rules: {
          department: [
            { required: true, message: '请输入', trigger: 'blur' }
          ],
          city: [
            { required: true, message: '请输入', trigger: 'blur' }
          ],
          store: [
            { required: true, message: '请输入', trigger: 'blur' }
          ],
          flow_id: [
            { required: true, message: '请选择', trigger: 'change' }
          ],
          applyUse: [
            { required: true, message: '请选择', trigger: 'change' }
          ],
          remarks: [
            { required: false, message: '请输入', trigger: 'blur' }
          ],
          wechatno: [
            { required: true, message: '请选择', trigger: 'change' }
          ],
          applyTemplateId: [
            { required: true, message: '请选择', trigger: 'change' }
          ],
          smsTemplateIdBynosub: [
            { required: true, message: '请选择', trigger: 'change' }
          ],
          smsTemplateIdBynocard: [
            { required: true, message: '请选择', trigger: 'change' }
          ]
        }
      }
    },
    computed: {
      id() {
        return this.$route.params.id
      },
      usefor() {
        const list = this.departments.filter(e => e.id == this.form.flow_id)
          if (list.length) {
            return list[0].usefor
          } else {
            return ''
          }
      },
      departmentId() {
        return this.$route.query.id
      },
      subTitle() {
        const subTitleList = ['发放微信券', '发放礼券', '发券平台']
        return subTitleList[this.sendType - 1]
      }
    },
    watch: {
      $route(to, from) {
        if (from.path.includes('/box/boxLook/addAndEdit2') || to.path.includes('/box/boxLook/addAndEdit2')) {
        } else {
          this.form = {}
        }
      }
    },
    activated() {
    },
    created() {
      console.log(this.userInfo(), 'userInfo')
      this.getRuleList()
      this.getDetails()
    },
    mounted() {
      let that = this
      // window.onbeforeunload = function(e) {
      //   if (that.$route.fullPath.includes('/headquarters-coupon/addAndEdit')) {//注意这里要菩换戍自己的当前页面的路由
      //     e = e || window.event
      //     //兼容IE8采Firefox 4之前的版本
      //     if (e) {
      //       e.returnValue = '关闭提示'
      //     }
      //     // Chrome，Safari，Firefox 4+，Opera 12+ , IE 9+return ‘关闭提示";
      //   } else {
      //     window.onbeforeunload = null
      //   }
      // }
    },
    // beforeRouteLeave(to, from, next) {
    //   if (!this.submitFlag) {
    //     this.$confirm({
    //       content: '系统可能不会保存您所做的更改,离开此页面?',
    //       onOk() {
    //         next()
    //       },
    //       onCancel() {
    //       }
    //     })
    //   } else {
    //     next()
    //   }
    // },
    
    beforeDestory() {
      // window.onbeforeunload = null
    },
    methods: {
      ...mapGetters(['nickname', 'avatar', 'userInfo']),
      
      //检测是否有未开卡
      checkCard(v) {
        this.form.isCard = v ? 1 : 2
      },

      //检测是否有未关注
      checkFollow(v) {
        this.form.isFollow = v ? 1 : 2
      },
      // 上移
      handleUp(index) {
        if (index === 0) return
        let temp = this.form.chooseVoucherRule[index - 1]
        this.$set(this.form.chooseVoucherRule, index - 1, this.form.chooseVoucherRule[index])
        this.$set(this.form.chooseVoucherRule, index, temp)
      },

      // 下移
      handleDown(index) {
        if (index === this.form.chooseVoucherRule.length - 1) return
        let i = this.form.chooseVoucherRule[index + 1]
        this.$set(this.form.chooseVoucherRule, index + 1, this.form.chooseVoucherRule[index])
        this.$set(this.form.chooseVoucherRule, index, i)
      },

      // 关联新的优惠券
      handleAddAssociatedCoupon() {
        this.form.chooseVoucherRule.push(
          {
            id: '',
            name: '',
            num: 1,
            amtAcount: '',
            couType: '',
            vouDis: '',
            description: ''
          }
        )
      },

      // 删除关联优惠券
      handleDeletAssociatedCoupon(index) {
        if (this.form.chooseVoucherRule.length < 2) {
          this.$message.info('至少要关联一种优惠券！')
          return
        }
        this.form.chooseVoucherRule.splice(index, 1)
      },
      filterOption(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        )
      },

      // 获取券详情
      getDetails() {
        this.sendType = this.$route.query.sendType
        this.form.remarks = this.$route.query.remarks ? this.$route.query.remarks : ''
        this.spinning = true
        const data = {
          id: this.id
        }
        addAndEditCoupon(data).then(res => {
          this.spinning = false
          if (res.code === 200) {
            const { oaflows, wechatInfos, showPageVoList, smstempList, applyUseList } = res.data
            this.departments = oaflows.records
            this.wechatInfos = wechatInfos
            this.showPageVoList = showPageVoList
            this.smstempList = smstempList
            this.applyUseList = Object.keys(applyUseList)
            this.form.flow_id = this.departmentId ? Number(this.departmentId) : 0
          } else {
            this.$message.error(res.msg || res.message)
          }
        }).catch(err => {
          this.spinning = false
        })
      },

      // 关联优惠券-分页
      handleCouponCurrentChange(current, size) {
        this.couponCurrent = current
        this.getRuleList()
      },

      // 关联优惠券-优惠券
      getRuleList() {
        const data = {
          'awardIds': [],
          'couponName': '',
          'notNullParam': [],
          'ruleIds': [],
          'types': ['VOU3', 'VOU4'],
          'current': this.couponCurrent,
          'size': this.couponPageSize,
          'ownerIds': [42293],
          'filterOwnerIds': []
        }
        ruleList(data).then(res => {
          if (res.code === 200) {
            const { records, total } = res.data
            this.ruleList = records
            this.couponTotal = total
          } else {
            this.$message.error(res.msg || res.message)
          }
        })
      },

      // 监听关联优惠券-优惠券
      ruleChange(item, index) {
        const { vouName, amtAcount, couType, vouDis, pp, description } = item
        this.form.chooseVoucherRule[index].name = vouName
        this.form.chooseVoucherRule[index].amtAcount = amtAcount
        this.form.chooseVoucherRule[index].couType = couType
        this.form.chooseVoucherRule[index].vouDis = vouDis
        this.form.chooseVoucherRule[index].pp = pp
        this.form.chooseVoucherRule[index].description = description
      },

      //提交
      handleSubmit() {
        const that = this
        this.$refs.rulesForm.validate(valid => {
          if (valid) {
            if (this.sendType != 3) {
              if (!this.$refs.sendUser.checkSendUser()) {
                this.$message.info('请先添加发放对象！')
                return
              }
            }
            this.submitFlag = true
            const list = this.departments.filter(e => e.id == this.form.flow_id)
            const data = {
              id: this.id,
              ...this.form,
              flow_id: this.departmentId ? this.form.flow_id : '',
              department: list.length ? list[0].department : this.form.department,
              applyUse: this.usefor
            }
            submit(data).then(res => {
              if (res.code === 200) {
                // this.submitFlag = false
                if (this.sendType == 1) {
                  this.$info({
                    title: '提交成功！消息已发送～',
                    icon: 'none',
                    okText: '返回',
                    closable: false,
                    onOk() {
                      that.$router.go(-1)
                    }
                  })
                } else {
                  this.$confirm({
                    title: '提交成功！',
                    icon: 'none',
                    closable: false,
                    okText: '打印券码',
                    cancelText: '返回',
                    onOk() {
                      const data = {
                        pageId: that.id
                      }
                      printDetails(data).then(res => {
                        if (res.code === 200) {
                          const data = decodeURIComponent(JSON.stringify(res.data))
                          that.$router.push(`/headquarters-coupon/print/1?data=${data}`)
                        } else {
                          that.$message.warning(res.msg || res.message)
                        }
                      })
                    },
                    onCancel() {
                      that.$router.go(-1)
                    }
                  })
                }
              } else {
                this.submitFlag = false
                this.$message.error(res.msg || res.message)
              }
            })

          } else {
            return false
          }
        })
      }
    }
  }
</script>
<style scoped>

  .association-list /deep/ td {
    padding-bottom: 0 !important;
  }
  .association-list{
    max-width: 100%;
  }

  .hidden-title /deep/ .ant-form-item-label > label {
    visibility: hidden;
  }
  .description{
    display: inline-block;
    vertical-align: top;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 1;
    word-break: break-all; /* 追加这一行代码 */
    /* autoprefixer: off */
    -webkit-box-orient: vertical;
    /* autoprefixer: on */
    margin-bottom: 24px;

  }
</style>
